<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="下单时间" prop="createTime">
          <el-date-picker @change="createDayChange" v-model="createTime" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                </el-date-picker>
        </el-form-item>
        <el-form-item label="用户名" prop="fuwuPerson">
          <el-input v-model="queryParams.fuwuPerson" placeholder="请输入用户名" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="用户电话" prop="fuwuPhone">
          <el-input v-model="queryParams.fuwuPhone" placeholder="请输入用户电话" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="下单项目" prop="projectId">
          <el-select multiple v-model="queryParams.projectId" placeholder="请选择下单项目">
            <el-option v-for="contract in projectArray" :key="contract.id" :label="contract.projectName"
              :value="contract.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单金额" prop="amount">
          <el-input v-model="queryParams.amountMin" placeholder="最小金额" clearable size="small"
            @keyup.enter.native="handleQuery" class="maxNum"/>
            <span class="line">—</span>
            <el-input v-model="queryParams.amountMax" placeholder="最大金额" clearable size="small"
            @keyup.enter.native="handleQuery" class="maxNum"/>
        </el-form-item>
        <el-form-item label="服务技师" prop="nickName">
          <el-input v-model="queryParams.nickName" placeholder="请输入服务技师" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="技师电话" prop="phonenumber">
          <el-input v-model="queryParams.phonenumber" placeholder="请输入技师电话" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="出行方式" prop="chuxingType">
          <el-select clearable v-model="queryParams.chuxingType" placeholder="请选择出行方式">
            <el-option v-for="contract in chuxingTypeArray" :key="contract.dictValue" :label="contract.dictLabel"
              :value="contract.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券" prop="couponsFlag">
          <el-select clearable v-model="queryParams.couponsFlag" placeholder="请选择优惠券">
            <el-option v-for="contract in couponsFlagArray" :key="contract.dictValue" :label="contract.dictLabel"
              :value="contract.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款方式" prop="payChannel">
          <el-select multiple v-model="queryParams.payChannel" placeholder="请选择付款方式">
            <el-option v-for="contract in payChannelArray" :key="contract.dictValue" :label="contract.dictLabel"
              :value="contract.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="tabList" @selection-change="handleSelectionChange">
        <el-table-column label="订单编号" align="center" prop="orderNo" />
        <el-table-column label="付款日期" align="center" prop="paymentTime" />
        <el-table-column label="退款申请时间" align="center" prop="createTime" />
        <el-table-column label="订单详情" align="center" prop="" >
          <template slot-scope="scope">
            <div @click="lookDetails(scope.row)" style="color:cornflowerblue;cursor: pointer;">查看详情</div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" prop="totalAmount" />
        <el-table-column label="出行方式" align="center" prop="chuxingType" :formatter="chuxingTypeformatter" />
        <el-table-column label="优惠券" align="center" prop="zhekouAmount" :formatter="couponsFlagformatter"/>
        <el-table-column label="付款方式" align="center" prop="payChannel" :formatter="payChannelformatter"/>
        <el-table-column label="实付(元)" align="center" prop="payAmount" />
        <el-table-column label="应退(元)" align="center" prop="actualRefund">
          <template slot-scope="scope">
            <!--已确认状态 有且只有确认权限时有输入框可再次修改确认，同时有确认和退款权限不展示输入框 -->
            <!-- <el-input v-if="(scope.row.refundStatus== '0' && $auth.hasPermi('admin:orderRefund:edit')) 
                || (scope.row.refundStatus== '1' && $auth.hasPermi('admin:orderRefund:edit') && !$auth.hasPermi('admin:orderRefund:pass'))" 
              type="number" v-model="scope.row.actualRefund" :max="scope.row.payAmount" @input="e => actualRefundChange(e, scope.$index)" placeholder="请输入"></el-input> -->
            <div>{{scope.row.actualRefund}}</div>
          </template>
        </el-table-column>
        <el-table-column label="平台退款(元)" align="center" prop="platRefund">
          <template slot-scope="scope">
            <!-- <el-input v-if="(scope.row.refundStatus== '0' && $auth.hasPermi('admin:orderRefund:edit')) 
                  || (scope.row.refundStatus== '1' && $auth.hasPermi('admin:orderRefund:edit') && !$auth.hasPermi('admin:orderRefund:pass'))" 
                type="number" v-model="scope.row.platRefund" :max="scope.row.actualRefund" @input="e => pttkChange(e, scope.$index)" placeholder="请输入"></el-input> -->
            <div>{{scope.row.platRefund}}</div>
          </template>
        </el-table-column>
        <el-table-column label="技师退款(元)" align="center" prop="commissionRefund"/>
        <el-table-column label="操作" align="center" prop="">
          <template slot-scope="scope">
            <div v-if="scope.row.refundStatus== '0'">
              <div v-if="$auth.hasPermi('admin:orderRefund:edit')" @click="refundEditClick(scope.row)" style="color:cornflowerblue;cursor: pointer;" v-hasPermi="['admin:orderRefund:edit']">确认</div>
              <div v-else>待确认</div>
            </div>
            <div v-else-if="scope.row.refundStatus== '1'">
              <!-- 同时有确认和退款权限 展示退款 -->
              <div v-if="$auth.hasPermi('admin:orderRefund:edit')" @click="refundEditClick(scope.row)" style="color:cornflowerblue;cursor: pointer;" v-hasPermi="['admin:orderRefund:edit']">确认</div>
              <div v-if="$auth.hasPermi('admin:orderRefund:pass')" @click="refundClick(scope.row)" style="color:cornflowerblue;cursor: pointer;" v-hasPermi="['admin:orderRefund:pass']">退款</div>
              <div v-if="!$auth.hasPermi('admin:orderRefund:pass') && !$auth.hasPermi('admin:orderRefund:edit')">已确认</div>
            </div>
            <div v-else>已退款</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      <el-dialog title="订单详情" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
        <div class="orderCont">
          <div>
            <span>用户名</span>
            <em>{{ orderDetails.fuwuPerson }}</em>
          </div>
          <div>
            <span>用户电话</span>
            <em>{{ orderDetails.fuwuPhone }}</em>
          </div>
          <div>
            <span>下单项目</span>
            <em v-for="name in orderDetails.projectNames">{{ name }} </em>
          </div>
          <div>
            <span>服务技师</span>
            <em>{{ orderDetails.nickName }}</em>
          </div>
          <div>
            <span>技师电话</span>
            <em>{{ orderDetails.phonenumber }}</em>
          </div>
          <div>
            <span>技师接单状态</span>
            <em>{{ orderDetails.statusName }}</em>
          </div>
          <div>
            <span>服务地址</span>
            <em>{{ orderDetails.fuwuAddr }}</em>
          </div>
          <div class="block">
            <el-timeline :reverse="reverse">
              <el-timeline-item
                v-for="(activity, index) in locations"
                :key="index"
                :timestamp="activity.createTime">
                  <h4>{{activity.createTypeName}}</h4>
                  <p>{{activity.addrDetail}}</p>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
        <div slot="footer" class="quesEditBtn">
          <el-button @click="cancel">确 认</el-button>
        </div>
      </el-dialog>

      <el-dialog title="退款确认" :close-on-click-modal="false" :visible.sync="childOpen" width="1400px" append-to-body>
        <el-table v-loading="loading" :data="refundChildList">
          <el-table-column label="订单编号" align="center" prop="orderNo" />
          <el-table-column label="支付编号" align="center" prop="orderSn" />
          <el-table-column label="类型" align="center" prop="createType" :formatter="createTypeFormatter"/>
          <el-table-column label="项目" align="center" prop="projectNames" />
          <el-table-column label="实付(元)" align="center" prop="payAmount" />
          <el-table-column label="平台收益" align="center" prop="platIncome" />
          <el-table-column label="技师收益" align="center" prop="jishiIncome" />
          <el-table-column label="推广佣金" align="center" prop="promotion" />
          <el-table-column label="应退(元)" align="center" prop="actualRefund">
            <template slot-scope="scope">
              <!--已确认状态 有且只有确认权限时有输入框可再次修改确认，同时有确认和退款权限不展示输入框 -->
              <el-input v-if="((refundStatus== '0' || refundStatus== '1') && $auth.hasPermi('admin:orderRefund:edit'))" 
                type="number" v-model="scope.row.actualRefund"  @change="e => actualRefundChange(e, scope.$index)" placeholder="请输入"></el-input>
              <div v-else>{{scope.row.actualRefund}}</div>
            </template>
          </el-table-column>
          <el-table-column label="平台退款(元)" align="center" prop="platRefund">
            <template slot-scope="scope">
              <el-input v-if="((refundStatus== '0' || refundStatus== '1') && $auth.hasPermi('admin:orderRefund:edit'))" 
                  type="number" v-model="scope.row.platRefund"  @change="e => pttkChange(e, scope.$index)" placeholder="请输入"></el-input>
              <div v-else>{{scope.row.platRefund}}</div>
            </template>
          </el-table-column>
          <el-table-column label="技师退款(元)" align="center" prop="commissionRefund"/>
          <el-table-column label="推广佣金退款(元)" align="center" prop="promotionRefund"/>
        </el-table>
        <div slot="footer" class="quesEditBtn">
          <el-button @click="refundEditSubmit">确 认</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
    
  <script>
  import { refundList, refundDetail, refundEdit, refundPass, refundChildList, refundCalculate} from "@/api/collectionBill/collectionBill";
  import { projectList} from "@/api/orderList/orderList";
  export default {
    name: "Knowledge",
    components: {
    },
    data() {
      return {
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 表格数据
        tabList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        companyTypeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderNo:null,
          createDay:null,
          fuwuPerson:null,
          fuwuPhone:null,
          projectId:null,
          amountMin:null,
          amountMax:null,
          amount:null,
          nickName:null,
          phonenumber:null,
          chuxingType:null,
          couponsFlag:null,
          payChannel:null,
        },
        createTime: '',
        createTimeStart: '',
        createTimeEnd: '',
        projectArray:[],//下单项目
        chuxingTypeArray:[],//出行方式
        couponsFlagArray:[],//优惠券
        payChannelArray:[],//付款方式
        orderDetails:{},
        orderStatusArray:[],
        childOpen:false,
        refundOrderNo:'',
        refundOrderInviteType:'',
        refundChildList:[],
        refundStatus: null,
        orderLocationTypeArray:[],
        locations:[],
        reverse:false,
      };
    },
    created() {
      this.getList();
      this.pjList()
       //在字典查询-出行方式
       this.getDicts("chuxing_type").then(response => {
        this.chuxingTypeArray = response.data;
      });
      //优惠券
      this.getDicts("is_coupons_flag").then(response => {
        this.couponsFlagArray = response.data;
      });
      //付款方式
      this.getDicts("pay_channel").then(response => {
        this.payChannelArray = response.data;
      });
      //状态
      this.getDicts("order_status").then(response => {
        this.orderStatusArray = response.data;
      });
      //订单操作类型
      this.getDicts("order_location_type").then(response => {
        this.orderLocationTypeArray = response.data;
      });
    },
    methods: {
      //应付
      actualRefundChange(e,index){
        let data = JSON.parse(JSON.stringify(this.refundChildList))
        let sf =  data[index].payAmount
        let priceA = data[index].platRefund
        e = parseInt(e) > parseInt(sf) ? sf : e
        data[index].actualRefund = e
        if(priceA) {
          refundCalculate({
            inviteType: this.refundOrderInviteType, 
            actualRefund:e, 
            platRefund:priceA,
            payAmount:data[index].payAmount,
            promotion:data[index].promotion
          }).then(response => {
            data[index].commissionRefund = response.data.commissionRefund
            data[index].promotionRefund = response.data.promotionRefund
          });
        }
        this.refundChildList = data
      },
      //平台退款
      pttkChange(e,index){
        let data = JSON.parse(JSON.stringify(this.refundChildList))
        let yf = data[index].actualRefund
        e = parseInt(e) > parseInt(yf) ? yf : e
        data[index].platRefund = e
        if(yf) {
          refundCalculate({
            inviteType: this.refundOrderInviteType, 
            actualRefund:yf, 
            platRefund:e,
            payAmount:data[index].payAmount,
            platIncome:data[index].platIncome,
            promotion:data[index].promotion
          }).then(response => {
            data[index].commissionRefund = response.data.commissionRefund
            data[index].promotionRefund = response.data.promotionRefund
          });
        }
        this.refundChildList = data
      },
      handleEdit(index, row) {
        console.log(index, row);
      },
      handleDelete(index, row) {
        console.log(index, row);
      },
      createDayChange() {
        this.createTimeStart = this.createTime[0] 
        this.createTimeEnd = this.createTime[1]
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.queryParams.createTimeStart = this.createTimeStart;
        this.queryParams.createTimeEnd = this.createTimeEnd;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.createTime = ''
        this.createTimeStart = ''
        this.createTimeEnd = ''
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 查询产品入库列表 */
      getList() {
        this.loading = true;
        refundList(this.queryParams).then(response => {
          this.tabList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      refundEditClick(row){
        this.refundChildList = [];
        this.refundOrderNo = row.orderNo
        this.refundOrderInviteType = row.inviteType
        this.refundStatus = row.refundStatus;
        refundChildList(row.orderNo).then(response => {
          this.refundChildList = response.data;
          this.childOpen = true;
        });
      },
      refundEditSubmit(){
        var that = this;
        this.$confirm('确认修改', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var list = that.refundChildList.filter(el => {return el.actualRefund > 0}).map(el => {
            return {
              id: el.id,
              actualRefund: el.actualRefund,
              platRefund: el.platRefund
            }
          })
          console.log(list)
          return refundEdit({
            orderNo: that.refundOrderNo,
            children: list
          });
        }).then(() => {
          this.$message({message: '退款成功',type: 'success'});
          this.childOpen = false;
          this.getList();

        })
      },
      refundClick(row){
        this.$confirm('确认退款', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return refundPass({
            orderNo: row.orderNo
          });
        }).then(() => {
          this.$message({message: '退款成功',type: 'success'});
          this.getList();

        })
      },
      //下单时间
      createTimeChange() {
        this.createTimeStart = this.createTime[0] 
        this.createTimeEnd = this.createTime[1]
      },
      //出行方式
      chuxingTypeformatter(row, column) {
        return this.selectDictLabel(this.chuxingTypeArray, row.chuxingType) + " ￥" + row.chuxingFei;
      },
      //优惠券
      couponsFlagformatter(row, column) {
        return row.zhekouAmount ? "￥" + row.zhekouAmount : "无";
      },
      //付款方式
      payChannelformatter(row, column) {
        return this.selectDictLabel(this.payChannelArray, row.payChannel);
      },
      lookDetails(row){
        this.orderDetails = {}
        var that = this;
        refundDetail({"orderNo":row.orderNo}).then(response => {
          this.orderDetails = response.data;
          this.orderDetails.statusName = this.selectDictLabel(this.orderStatusArray, this.orderDetails.orderStatus);
          this.locations = response.data.locations;
            if (this.locations.length > 0){
              this.locations = this.locations.map(i =>{return {
                ...i,
                createTypeName: that.orderLocationTypeformatter(i.createType)
              }})
            }
        });
        this.open = true
      },
      cancel(){
        this.open = false
      },
      cancelEdit(){
        this.childOpen = false
      },
      createTypeFormatter(row){
        let type = row.createType;
        switch(type){
          case '1':
            type = '下单'
            break;
          case '2':
            type = '加钟'
            break;          
          case '3':
            type = '升级'
            break;
        }
        return type;
      },
      orderLocationTypeformatter(createType) {
        return this.selectDictLabel(this.orderLocationTypeArray, createType);
      },
      pjList() {
        projectList().then(response => {
          this.projectArray = response.data;
        });
      },
    }
  };
  </script>
  <style lang="scss" scoped>
    .orderCont{
      width: 90%;
      margin: 0 auto;
      div{
        line-height: 28px;
        display: flex;
        justify-content: left;
        align-content: left;
        span{
          display: inline-block;
          width: 110px;
          font-size: 14px;
          color:#666;
        }
        em{
          display: inline-block;
          font-style: normal;
          font-size: 14px;
          color:#333;
        }
      }
    }
      .quesEditBtn{
        text-align: center;
      }
      .money{
        padding: 5px 10px;
        width: 60px;
        border:1px solid #999;
        font-size: 14px;
        color:#333;
        text-align: center;
      }
      .maxNum{
        width: 100px;
      }
      .line{
        margin: 0 10px;
      }
  </style>
    